XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	// We need the castle infos to send paras to the right place :)
	_random_industrial = DM_Chapter_Location;
	_random_industrial_pos = DM_Chapter_Location select XF_MAP_LOCATION_CENTER;
	_random_industrial_size = DM_Chapter_Location select XF_MAP_LOCATION_SIZE;
	_surrounding_towns = DM_Variable;

	_vip_found = false;
	_vip_alive = true;
	_vip_updated = false;
	_vip_lead_updated = false;
	
	_hostage_found = false;
	_hostage_alive = true;
	_hostage_updated = false;
	_hostage_dead = false;
	
	_prototype_destroyed = false;
	_prototype_updated = false;
	_player_detected = false;

	_enemy_initial_counts = ([_random_industrial_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 3;
	_detected_time = time;

	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([_random_industrial_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_vip_found = ["jip_vip_found",false] call XNetGetJIP;
		_vip_alive = ["jip_vip_alive",true] call XNetGetJIP;
		_vip_lead = ["jip_vip_lead",false] call XNetGetJIP;
		_hostage_found = ["jip_hostage_found",false] call XNetGetJIP;
		_hostage_alive = ["jip_hostage_alive",true] call XNetGetJIP;
		_prototype_destroyed = ["jip_target_destroyed",false] call XNetGetJIP;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		if (_vip_found and !_vip_updated) then {
			_vip_updated = true;
			["FindTheChemist","", "","",[],"Succeeded"] call XfMissionTask;
			"STR_MF_DC_FINDCHEMISTWIFE" call XfMissionMessageToAll;
			
			_wife_pos_hiding = [];
			_i_tries = 30;
			while { ((count _wife_pos_hiding) > 0) && (_i_tries > 0) } do {
				_wife_town = (_surrounding_towns call XfRandomArrayVal);
				_building_hide_pos = ([(_wife_town select XF_MAP_LOCATION_CENTER),(_wife_town select XF_MAP_LOCATION_SIZE),"HIDE"] call XfMissionBuildingAreaPosASL);
				if (count _building_hide_pos > 0) then {
					_wife_pos_hiding = _building_hide_pos select 0;
				};
				_i_tries = _i_tries - 1;
			};
			if ((count _wife_pos_hiding) <= 0) then {
				_wife_pos_hiding = [(_wife_town select XF_MAP_LOCATION_CENTER),(_wife_town select XF_MAP_LOCATION_SIZE) / 2] call XfMissionRanObjectivePos;
			};
			_grp = ["CIV"] call x_creategroup;
			DM_Hostage = ["RU_Secretary4",_grp,_wife_pos_hiding,"RESCUE",["","","jip_hostage_found","jip_hostage_alive"],"doStop this;","NONE"] call XfMissionCreateMissionUnit;
			DM_Hostage setPosASL _wife_pos_hiding;

			["FindTheWife","Find the Chemist's Wife", "The wife of the Chemist is being held hostage by the enemy. This is the only reaon why he has been working for them. You will need to find her, then lead the Chemist to her when you've found her.<br /><br />She must be in a town nearby because she could visit him regularly.<br />Be quick and don't let the chemist die!","",[],"Created"] call XfMissionTask;
			["DestroyPrototype","Destroy the prototype", "We arrived later than we expected, a prototype vehicle equipped with the new rockets has already been built.<br /><br />It is hidden somewhere near the factory, probably in one of the nearby towns since it needs to get back to the factory regularly for the tests.<br />We can't leave this vehicle intact!","",[],"Created"] call XfMissionTask;
			
			_surrounding_towns spawn {
				{
					_town_pos = _x select XF_MAP_LOCATION_CENTER;
					_town_size = _x select XF_MAP_LOCATION_SIZE;
					_town_unique = Format["chapter1_%1",(_x select XF_MAP_LOCATION_UNIQUENAME)];
					[d_enemy_side,[_town_pos,_town_size],true] call XfMissionPopulateLocation;
					[d_enemy_side,[_town_pos,_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;	
					[false,[_town_unique, _town_pos, "ELLIPSE", "ColorBlue", [_town_size,_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
				} foreach _this;
			};
		};
		
		if (_vip_updated and _hostage_found and !_hostage_updated) then {
			_hostage_updated = true;
			["LeadTheChemist","Lead the Chemist to his Wife", "Now that you found the Chemist's Wife, go get her husband and lead him there.","",[],"Created"] call XfMissionTask;
			["FindTheWife","", "","",[],"Succeeded"] call XfMissionTask;
			[DM_VIP,group DM_VIP,getPos DM_VIP,"LEAD",["The chemist has retrieved his wife. Congratulations!","You did your best...","jip_vip_lead","jip_vip_alive",[getPos DM_Hostage,[20,20],0,false]],"doStop this; removeAllWeapons this;"] call XfMissionCreateMissionUnit;
			"STR_MF_DC_GETCHEMISTTOWIFE" call XfMissionMessageToAll;
		};
		if (_vip_updated and !_hostage_alive and !_hostage_dead) then {
			_hostage_dead = true;
			["FindTheWife","", "","",[],"Failed"] call XfMissionTask;
			if (!_prototype_destroyed) then {
				"STR_MF_DC_WIFEISDEAD1" call XfMissionMessageToAll;
			} else {
				"STR_MF_DC_WIFEISDEAD2" call XfMissionMessageToAll;
				_chapter_succeeded = false;
				DM_Mission_Chapter_CanRun = false;
			};
		};
		
		if (_prototype_destroyed and !_prototype_updated) then {
			_prototype_updated = true;
			["DestroyPrototype","", "","",[],"Succeeded"] call XfMissionTask;
			if (_hostage_alive) then {
				"STR_MF_DC_PROTOTYPE1" call XfMissionMessageToAll;
			} else {
				"STR_MF_DC_PROTOTYPE2" call XfMissionMessageToAll;
				_chapter_succeeded = false;
				DM_Mission_Chapter_CanRun = false;
			};
		};
		
		if (_vip_lead && !_vip_lead_updated && _hostage_alive) then {
			_vip_lead_updated = true;
			["LeadTheChemist","", "","",[],"Succeeded"] call XfMissionTask;
			"STR_MF_DC_TOGETHER" call XfMissionMessageToAll;
			if (vehicle DM_VIP != DM_VIP) then {
				DM_VIP allowDamage false;
				DM_VIP action ["eject",vehicle DM_VIP];
			};
			if (alive DM_VIP && alive DM_Hostage) then {
				[DM_VIP] joinSilent (group DM_Hostage);
				DM_Hostage domove getPos DM_VIP;
				sleep 3;
				DM_Hostage domove getPos DM_VIP;
			};
			sleep 15;
		};

		if (_vip_found && _hostage_found && _vip_lead && _prototype_destroyed && _vip_alive && _hostage_alive && _vip_lead_updated) then {
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
		};

		if (!_vip_alive) then {
			_chapter_succeeded = false;
			DM_Mission_Chapter_CanRun = false;
		};

		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"STR_MF_PLAYERDETECTED" call XfMissionMessageToAll;
			_detected_time = time;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements > 0) AND !_vip_updated) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[_random_industrial_pos,_random_industrial_size],"PARA",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};

	_players_found = true;
	While {DM_Mission_Mission_CanRun && (([_random_industrial_pos,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 3 && _players_found} do {
		sleep 5;
		_players_found = false;
		{
			if ([(getPos _x), _random_industrial_pos, 600] call XfPointInCircle) exitWith { _players_found = true; };
		}foreach playableUnits;
	};

	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_industrial","_random_industrial_pos","_random_industrial_size","_troops_power","_troops_coeff","_grpSoldiers","_i","_factory_pos_hiding","_wife_pos_hiding","_prototype_pos","_grpUAZ"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	_random_industrial = [];
	_surrounding_towns = [];
	_building = objNull;
	_i_tries = 30;
	while { ((count _random_industrial) <= 0) && (_i_tries > 0) } do {
		_random_industrial = [XF_MAP_LOCATION_TYPE_INDUSTRIAL] call XfMissionGetRandomSpot;
		if ((count _random_industrial) > 0) then {
			_random_industrial_pos = _random_spot select XF_MAP_LOCATION_CENTER;
			_random_industrial_size = _random_spot select XF_MAP_LOCATION_SIZE;
			
			_nearby_towns = [_random_industrial_pos,[_random_industrial_size, 2000],True] call XfMissionGetTownsInRange
			if (count _nearby_towns >= 2) then {
				{
					_town_pos = _x select XF_MAP_LOCATION_CENTER;
					_town_size = _x select XF_MAP_LOCATION_SIZE;
					_objects = nearestObjects [_town_pos, ["Land_Hangar_2", "land_ibr_hangar", "Land_SS_hangar", "Land_Mil_Hangar_EP1"], _town_size];
					if (count _objects > 0) exitWith {
						_building = _objects call XfRandomArrayVal;
						_surrounding_towns set [ count _surrounding_towns, _x];
					}
				} foreach _nearby_towns;
				if (count _surrounding_towns > 0) then {
					_nearby_towns = _nearby_towns - _surrounding_towns;
					// We pack 2 other towns than the one with the vehicle in order to place the girl.
					_surrounding_towns set [ count _surrounding_towns, (_nearby_towns call XfRandomArrayVal)];
					_nearby_towns = _nearby_towns - _surrounding_towns;
					if (count _nearby_towns > 0) then {
						_surrounding_towns set [ count _surrounding_towns, (_nearby_towns call XfRandomArrayVal)];
					};
				};
			};
		};
		_random_industrial = [];
		_surrounding_towns = [];
		_building = objNull;
		_i_tries = _i_tries - 1;
	};
	if ((count _random_industrial) <= 0) exitWith {"STR_MF_RANDOMSITEFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_industrial_name = _random_industrial select XF_MAP_LOCATION_DISPLAYNAME;
	
	DM_Chapter_Location = _random_industrial;
	DM_Chapter_Position = _random_industrial_pos;
	
	// This indicates where the mission takes place
	[_random_industrial_pos,_random_industrial_size,_random_industrial_name] call XfMissionCurrentPosition;
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_industrial_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};

	// The marker which indicates the buildings zone
	[false,["chapter1_random_industrial_zone", _random_industrial_pos, "ELLIPSE", "ColorRed", [_random_industrial_size,_random_industrial_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_random_industrial_position",getPos _building, "ICON", "ColorRed", [1,1],_random_industrial_name,0,"hd_objective","",0.6]] call XfMissionMarker;

	["jip_vip_found",false] call XNetSetJIP;
	["jip_vip_alive",true] call XNetSetJIP;
	["jip_hostage_found",false] call XNetSetJIP;
	["jip_hostage_alive",true] call XNetSetJIP;
	["jip_vip_lead",false] call XNetSetJIP;
	["jip_target_destroyed",false] call XNetSetJIP;
	
	DM_Variable = _surrounding_towns;
	
	_prototype_pos = getPos _building;
	_factory_pos_hiding = ([_random_industrial_pos,_random_industrial_size,"HIDE"] call XfMissionBuildingAreaPosASL) select 0;
	
	_grp = ["CIV"] call x_creategroup;
	DM_VIP = ["Doctor",_grp,_factory_pos_hiding,"RESCUE",["You freed the chemist, congratulations!","You did your best... the chemist died!","jip_vip_found","jip_vip_alive"],"doStop this;","NONE"] call XfMissionCreateMissionUnit;
	DM_VIP setPosASL _factory_pos_hiding;

	_grad = ["GRAD_RU",_prototype_pos,"ASSASSINATE",["","jip_target_destroyed"],"","CAN_COLLIDE"] call XfMissionCreateMissionObject;
	_grad lock true;
	
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_industrial_pos,350,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	
	_grpSoldiers = [d_enemy_side,[_random_industrial_pos,_random_industrial_size],["chapter1_random_industrial_zone","noveh","aware","buildings","fortify"],floor(random(5))] call XfMissionCreateFootmenGroup;
	_grpSoldiers = [d_enemy_side,[_random_industrial_pos,_random_industrial_size],["chapter1_random_industrial_zone","noveh","aware","buildings","ambush2"],floor(random(5))] call XfMissionCreateFootmenGroup;
	_grpSoldiers = [d_enemy_side,[_random_industrial_pos,_random_industrial_size],["chapter1_random_industrial_zone","noveh","aware","buildings"],floor(random(5))] call XfMissionCreateFootmenGroup;
	_grpUAZ = [d_enemy_side,[_random_industrial_pos,_random_industrial_size * 3],["chapter1_random_industrial_zone","onroad","aware"],5] call XfMissionCreateVehicleGroup;
	_grpUAZ = [d_enemy_side,[_random_industrial_pos,_random_industrial_size * 3],["chapter1_random_industrial_zone","onroad","aware"],5] call XfMissionCreateVehicleGroup;
	
	["FindTheChemist","Find the Chemist", "A brilliant Chernarus chemist is being held at the Polana factory.<br />Our reports indicate that he is being forced to work on a new type of Lethal Gaz Rocket. We cannot let the enemy use chemical weapons, it could kill many innocents and many fellow soldiers.<br /><br />We don't have the time to push the investigation further, we need to stop them NOW.<br /><br />Go find the chemist, free him and convince him to work for us instead.<br />We want this man and we want him alive!<br />Good luck!","",[],"Created"] call XfMissionTask;
	
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_industrial_pos,750],DM_Mission_AirSupport] call XfMissionCallAirSupport;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"STR_MF_DANGEROUSWEAPON" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE1" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;